<template>
  <el-card v-if="viewdata.questions.length != 0" class="box-card">
    <div @click="viewdata.isShow = true" class="topbox">{{viewdata.number + 1}}/{{viewdata.questions.length}}</div>
    <div class="contentbox">
      <div class="title">
        <span>({{optype(viewdata.questions[viewdata.number].type)}})</span>
        {{viewdata.questions[viewdata.number].title}}</div>
      <div v-if="viewdata.questions[viewdata.number].type=='tian'">
        <el-input type="text" v-model="viewdata.content" @input="changeInput"/>
        <hr>
      </div>
      <DanView :arr="viewdata.questions[viewdata.number].options" :current="viewdata.answers[viewdata.number]" @fnc="radioChange" v-if="viewdata.questions[viewdata.number].type=='dan' || viewdata.questions[viewdata.number].type=='pan'"></DanView>
      <DuoView :arr="viewdata.questions[viewdata.number].options" :record="viewdata.record" @fnc="chooseboxChange" v-if="viewdata.questions[viewdata.number].type=='duo'"></DuoView>
    </div>
    <div class="btnbox">
      <el-button type="default" @click="calc(-1, viewdata.questions[viewdata.number-1].type)" v-show="viewdata.number!=0">上一题</el-button>
      <el-button type="default" @click="calc(1, viewdata.questions[viewdata.number+1].type)" v-show="viewdata.number!=viewdata.questions.length-1">下一题</el-button>
    </div>
    <el-button style="width: 663px; margin-top: 1vh;" type="primary" @click="submit" v-if="viewdata.answers[viewdata.number] != '' && viewdata.questions.length == viewdata.answers.length && viewdata.questions.length-1 == viewdata.number">提交答题</el-button>
  </el-card>
  <!-- 题量对话框 -->
  <el-dialog v-model="viewdata.isShow" title="题目">
    <el-scrollbar height="350px">
      <div v-for="(item, index) in viewdata.questions" :key="item.code" :class="{numberBtn: true, numberBtnBColor: viewdata.answers[index]}" @click="numberCalc(index)">{{index+1}}</div>
    </el-scrollbar>
  </el-dialog>
  <!-- 下载练习 -->
  <el-button type="primary" @click="downloadFile" class="down">下载练习</el-button>
  <!-- 返回首页 -->
  <el-button @click="BackHome">返回首页</el-button>
</template>

<script setup>
  import DanView from '../../components/DanView.vue'
  import DuoView from '../../components/DuoView.vue'

  import { getexercisequestions, gettestquestions, downloadtext, settestrecords, setrecords, submittestpaper, submitanswers } from '../../api/question.js'

  import { ref, onBeforeMount, onBeforeUnmount, computed } from 'vue'

  import { useRoute, useRouter } from 'vue-router'

    const route = useRoute()
    const router = useRouter()
    // console.log('99999999', route.query.query)

  const viewdata = ref({
    isShow: false,
    record: [], // 本道多选题记录，index对应A、B、C等序号，true表述被选中
    content: '', // 填空题记录
    answers: [''], // 本次答案
    number: 0, // 题号
    questions: [], // 问题
    type: '', // 类型
    subject: '', // 科目
    isSubmit: false, // 是否提交答案
    questionIds: [],
    // 下载练习的相关配置
    url: 'http://127.0.0.1:8000/questionlist.docx',
    isShowProgress: false,
    progress: 0,
    time: 0,
    scores: [],
    testpaper: ''
  })
  const optype = computed(() => (type) => {
    switch (type) {
      case 'tian': return '填空'
      case 'duo': return '多选'
      case 'pan': return '判断'
      case 'dan': return '单选'
    }
  })
  onBeforeMount(() => {
    viewdata.value.type = route.query.type
    viewdata.value.subject = route.query.subject
    if (route.query.time) {
      // 试卷
      viewdata.value.time = route.query.time
      viewdata.value.testpaper = route.query.testpaper
      gettestquestions({
        username: localStorage.getItem('token'),
        time: route.query.time,
        isnew: route.query.isnew
      }).then(res => {
        viewdata.value.questions = res.questions
        viewdata.value.answers = res.answers
        viewdata.value.questionIds = res.questionIds
        viewdata.value.scores = res.scores
        // console.log(res.scores)
        if (res.isNew) {
          // 新开第一道是多选题做特殊处理
          if (res.questions[0].type === 'duo') {
            const arr = []
            for (let i = 0; i < res.questions[0].options.length; i++) {
              arr.push(false)
            }
            viewdata.value.record = arr
          }
        } else {
          // 恢复第一道题处理
          if (res.questions[0].type === 'tian') {
            viewdata.value.content = res.answers[0]
          } else if (res.questions[0].type === 'duo') {
            const arr = []
            for (let j = 0; j < res.questions[0].options.length; j++) {
              if (res.answers[0] !== undefined && res.answers[0].indexOf(res.questions[0].options[j].code) !== -1) {
                arr.push(true)
              } else {
                arr.push(false)
              }
            }
            viewdata.value.record = arr
          }
        }
      })
    } else {
      // 练习或组卷
      // console.log(route.query.type)
      getexercisequestions({
        username: localStorage.getItem('token'),
        type: route.query.type,
        subject: route.query.subject,
        num: route.query.num,
        isnew: route.query.isnew
      }).then(res => {
        viewdata.value.questions = res.questions
        viewdata.value.answers = res.answers
        viewdata.value.questionIds = res.questionIds
        if (res.isNew) {
          // 新开第一道是多选题做特殊处理
          if (res.questions[0].type === 'duo') {
            const arr = []
            for (let i = 0; i < res.questions[0].options.length; i++) {
              arr.push(false)
            }
            viewdata.value.record = arr
          }
        } else {
          // 恢复第一道题处理
          if (res.questions[0].type === 'tian') {
            viewdata.value.content = res.answers[0]
          } else if (res.questions[0].type === 'duo') {
            const arr = []
              for (let j = 0; j < res.questions[0].options.length; j++) {
                if (res.answers[0] !== undefined && res.answers[0].indexOf(res.questions[0].options[j].code) !== -1) {
                  arr.push(true)
                } else {
                  arr.push(false)
                }
              }
            viewdata.value.record = arr
          }
        }
      })
    }
  })
  onBeforeUnmount(() => {
    // 退出前未提交答案，记录答题
    if (!viewdata.value.isSubmit) {
      if (viewdata.value.type !== '试卷') {
        setrecords({
          username: localStorage.getItem('token'),
          subject: viewdata.value.subject,
          type: viewdata.value.type,
          questionIds: viewdata.value.questionIds,
          answers: viewdata.value.answers
        })
      } else {
        settestrecords({
          username: localStorage.getItem('token'),
          time: viewdata.value.time,
          questionIds: viewdata.value.questionIds,
          answers: viewdata.value.answers
        })
      }
    }
  })
      // 修改单项选择答案
    const radioChange = (code) => {
      viewdata.value.answers.splice(viewdata.value.number, 1, code)
      // console.log(viewdata.value.answers)
    }
    // 修改多项选择答案
    const chooseboxChange = (index) => {
      // console.log(viewdata.value.record)
      viewdata.value.record.splice(index, 1, !viewdata.value.record[index])
      let str = ''
      for (let j = 0; j < viewdata.value.record.length; j++) {
        if (viewdata.value.record[j]) {
          str = str + viewdata.value.questions[viewdata.value.number].options[j].code
        }
      }
      viewdata.value.answers.splice(viewdata.value.number, 1, str)
      // console.log(viewdata.value.answers)
    }
    // 修改填空答案
    const changeInput = (value) => {
      // viewdata.value.content = e.detail.value
      viewdata.value.answers[viewdata.value.number] = value
      // console.log(viewdata.value.answers)
    }
    // 改变题目
    const calc = (n, type) => {
      // console.log(viewdata.value.number, n, type)
      if (type === 'dan' || type === 'pan') {
        danCalc(n)
      } else if (type === 'duo') {
        duoCalc(n)
      } else {
        tianCalc(n)
      }
    }
    // 下一题是单选/判断的处理
    const danCalc = (n) => {
      if (n === 1 && viewdata.value.number + 1 === viewdata.value.answers.length) {
        viewdata.value.answers.push('')
      }
      viewdata.value.number = viewdata.value.number + n
    }
    // 下一题是多选的处理
    const duoCalc = (n) => {
      viewdata.value.number = viewdata.value.number + n
      if (viewdata.value.questions[viewdata.value.number].type === 'duo' && viewdata.value.answers.length === viewdata.value.number) {
        const arr = []
        for (let i = 0; i < viewdata.value.questions[viewdata.value.number].options.length; i++) {
          arr.push(false)
        }
        viewdata.value.record = arr
        viewdata.value.answers.push('')
      } else {
        const arr = []
        for (let j = 0; j < viewdata.value.questions[viewdata.value.number].options.length; j++) {
          if (viewdata.value.answers[viewdata.value.number] !== undefined && viewdata.value.answers[viewdata.value.number].indexOf(viewdata.value.questions[viewdata.value.number].options[j].code) !== -1) {
            arr.push(true)
          } else {
            arr.push(false)
          }
        }
        viewdata.value.record = arr
      }
    }
    // 下一题是填空的处理
    const tianCalc = (n) => {
      viewdata.value.number = viewdata.value.number + n
      if (n === 1 && viewdata.value.answers.length === viewdata.value.number) {
        viewdata.value.answers.push('')
        viewdata.value.content = ''
      } else {
        viewdata.value.content = viewdata.value.answers[viewdata.value.number]
      }
    }
    // 从题目需要列表中改变题目的处理
    const numberCalc = (index) => {
      const length = index - viewdata.value.number
      // 判断选择的题是否有答案
      if (length > 0 && index >= viewdata.value.answers.length) {
        for (let i = viewdata.value.number + 1; i <= index; i++) {
          viewdata.value.answers.push('')
        }
        if (viewdata.value.questions[index].type === 'duo') {
          const arr = []
          for (let j = 0; j < viewdata.value.questions[index].options.length; j++) {
            arr.push(false)
          }
          viewdata.value.record = arr
        } else if (viewdata.value.questions[index].type === 'tian') {
          viewdata.value.content = ''
        }
      } else {
        // 有答案恢复记录
        if (viewdata.value.questions[index].type === 'duo') {
          const arr = []
          for (let j = 0; j < viewdata.value.questions[index].options.length; j++) {
            if (viewdata.value.answers[index] !== undefined && viewdata.value.answers[index].indexOf(viewdata.value.questions[index].options[j].code) !== -1) {
              arr.push(true)
            } else {
              arr.push(false)
            }
          }
          viewdata.value.record = arr
        } else if (viewdata.value.questions[index].type === 'tian') {
          viewdata.value.content = viewdata.value.answers[index]
        }
      }
      viewdata.value.number = index
      viewdata.value.isShow = false
    }

    const submit = () => {
      viewdata.value.isSubmit = true
      const errorIndexs = []
      const grades = []
      // 记录错题在questions中的编号
      for (let i = 0; i < viewdata.value.questions.length; i++) {
        if (viewdata.value.answers[i] !== viewdata.value.questions[i].answer) {
          errorIndexs.push(i)
          grades.push(0)
        } else {
          grades.push(1)
        }
      }
        if (viewdata.value.type !== '试卷') {
          submitanswers({
            username: localStorage.getItem('token'),
            type: viewdata.value.type,
            subject: viewdata.value.subject,
            answers: viewdata.value.answers,
            errorIndexs,
            questionIds: viewdata.value.questionIds,
            grades
          }).then(res => {
            // console.log("111")
            router.replace({
              name: 'grade',
              query: {
                time: res.time,
                type: viewdata.value.type
              }
            })
          })
        } else {
          submittestpaper({
            username: localStorage.getItem('token'),
            time: viewdata.value.time,
            answers: viewdata.value.answers,
            errorIndexs,
            questionIds: viewdata.value.questionIds,
            grades,
            scores: viewdata.value.scores
          }).then(res => {
            // console.log("111")
            router.replace({
              name: 'grade',
              query: {
                time: res.time,
                type: viewdata.value.type
              }
            })
          })
        }
      }
  // 下载练习
  const downloadFile = () => {
    const item = {
      questionIds: viewdata.value.questionIds
    }
    if (viewdata.value.type === '试卷') {
      item.scores = viewdata.value.scores
      item.testpaper = viewdata.value.testpaper
    } else {
      item.subject = viewdata.value.subject
      item.type = viewdata.value.type
    }
    downloadtext(item).then(res => {
      const fileName = viewdata.value.type === '试卷' ? viewdata.value.type : viewdata.value.subject + viewdata.value.type
      // const x = new window.XMLHttpRequest()
      //   x.open('GET', viewdata.value.url, true)
      //   x.responseType = 'blob'
      //   x.onload = () => {
      //       const url = URL.createObjectURL(x.response)
      //       const a = document.createElement('a')
      //       a.href = url
      //       a.target = '_blank'
      //       a.download = fileName
      //       document.body.append(a)
      //       a.click()
      //       document.body.removeChild(a)
      //   }
      //   x.send()

      const link = document.createElement('a') // 创建一个 a 标签用来模拟点击事件
      link.style.display = 'none'
      link.href = viewdata.value.url // 设置下载路径
      link.target = '_blank' // a标签点击后的跳转方式
      link.download = fileName // 自定义设置下载后的文件，不知道为什么没生效，之后再看看
      document.body.appendChild(link) // 页面添加 a 标签
      link.click() // 触发 a 标签点击事件，即触发点击下载
      document.body.removeChild(link) // 页面去除刚刚添加的 a 标签
    })
  }
  // 返回首页
  const BackHome = () => {
    router.push({
      name: 'home'
    })
  }
</script>

<style lang="less" scoped>
.box-card {
  width: 700px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
  .numberBtn {
    display: inline-block;
    border: 1px solid #000;
    border-radius: 50%;
    line-height: 50px;
    width: 50px;
    height: 50px;
    margin: 10px;
    text-align: center;
  }
  .numberBtnBColor {
    background-color: rgba(0,0,255,.5);
  }
  .topbox {
    background-color: #f8f8f8;
    height: 5vh;
    text-align: center;
    line-height: 5vh;
    margin: 2vh auto;
    font-size: 2.8vh;
  }
  .contentbox {
    box-sizing: border-box;
    background-color: #f8f8f8;
    padding: 1vh 3vw;
    margin: 2vh auto;
    font-size: 2.8vh;

    .title {
      margin-bottom: 2vh;
      font-weight: bold;
    }

    input {
      font-size: 2.8vh;
    }
  }
  .btnbox {
    display: flex;
    margin: 2vh auto;
    button {
      flex: 1;
    }
  }
  .down {
    position: fixed;
    bottom: 5vh;
    left: 50%;
    transform: translateX(-50%);
  }
</style>
